package com.syt.test

import java.awt.Rectangle

fun maxOf(a: Int, b: Int) = if (a > b) a else b

/**
 * @author  YuTian
 * @date  2020/6/9 9:11 上午
 * @功能 test04
 */
fun main() {
    var a = 1
    val s1 = "a is $a"
    println(s1)
    a++
    println(s1)
    var s2 = "${s1.replace("is", "was")}, but now is $a"
    println(s1 + "\t" + s2)
    println(maxOf(-1, 10))
    var b = 3
    println(if (a < b) a else b)

    println(parseInt("123"))
    println(parseInt("123"))

    var c = 9999L
    for (i in 10 .. 20 step 1) {
        c *= i
        println("c = ${c}")
    }

    printProduct("12.2", "12")

    println(getStringLength("1234556"))

    Thread.sleep(1000)

    val items = listOf("apple", "banana", "kiwifruit", "orange")
    for (item in items) {
        println(item)
    }
    for (item in items.indices) {
        println(items[item])
    }

    var index = 0
    while (index < items.size) {
        println("item at $index is ${items[index]}")
        index++
    }

    println(describe(1231245436236))
    println(describe("545"))
    println(describe(1))

    val list = listOf<String>("a", "b", "c")
    if (-1 !in 0..list.lastIndex) {
        println(" -1 is not in $list")
    } else {
        println(" -1 in $list")
    }

    for (x in 1..10 step 2) {
        print(x)
    }
    println()
    for (x in 9 downTo 0 step 4) {
        print(x)
    }
    println()

    /**
     * 只能判断输出一次，第一次判断成功就退出。
     */
    when {
        "orange" in items -> println("orange is juicy")
        "apple" in items -> println("apple is fine too")
    }

    val fruits = arrayListOf("banana", "avocado", "apple", "kiwifruit")
    fruits.add("pear")
    println("fruits = ${fruits}")
    println(fruits.filter { it.startsWith("a") })
    println(fruits
        .filter { it.startsWith("a") }
        .sortedBy { it })
    fruits
            // 过滤 -> a
        .filter { it.startsWith("a") }
            //排序
        .sortedBy { it }
            // 大写
        .map { it.toUpperCase() }
            // 迭代输出
        .forEach { println(it) }

}

fun parseInt(str: String): Int? =
    try {
        str.toInt()
    } catch (e: NumberFormatException) {
        // 类型装换异常，输出空
        null
}

fun printProduct(arg1: String, arg2: String) {
    val x = parseInt(arg1)
    val y = parseInt(arg2)

    if (x != null && y != null) {
        println(x * y)
    } else {
        println("'$arg1' or '$arg2' is not a number")
    }
}

fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        return obj.length
    }
    return null
}

fun describe(obj: Any): String =
    // 高级java switch
    when (obj) {
        1           -> "one"
        2           -> "two"
        "hello"     -> "greeting"
        is Long     -> "this is long"
        !is String  -> "not a string"
        else        -> "Unknown"
    }